package com.jukte.recipe.webservices;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.util.Log;

import com.jukte.recipe.db.DBAdapter;
import com.jukte.recipe.db.DataBaseManager;
import com.jukte.recipe.utils.Constants;

public class GetDataTask extends AsyncTask<Void, Integer, String> {
    private HashMap<Integer, String> datas;
    private ProgressDialog pd;

    private SharedPreferences prefs;
    private Editor edt;
    private DBAdapter mDB;
    
	private String[] tables = new String[]{"categories", "custom_ingredients", "directions",
			"ing_group", "ingredients", "recipe_sub_category_relation",
			"recipes", "sub_categories", "tips"};
	public GetDataTask(Context ctx, ProgressDialog pd) {
		mDB = new DBAdapter(ctx);
		datas = new HashMap<Integer, String>();
		this.pd = pd;
		
		prefs = ctx.getSharedPreferences("QUINOA", Context.MODE_PRIVATE);
        edt = prefs.edit();
	}
	
	@Override
	protected void onPreExecute() {}
	
	@Override
	protected String doInBackground(Void... params) {
		try {
			for (int j = 0; j < tables.length; j++) {
				getDataTable(j);
				publishProgress(j+1);
			}
			
		} catch (UnsupportedEncodingException e1) {
			Log.e("Exception", "" + e1.getMessage());
			return e1.getMessage();
			// e1.printStackTrace();
		} catch (ClientProtocolException e1) {
			Log.e("ClientProtocolException", "" + e1.getMessage());
			return e1.getMessage();
			// e1.printStackTrace();
		} catch (IOException e1) {
			Log.e("IOException", "" + e1.getMessage());
			return e1.getMessage();
			// e1.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
			return e.getMessage();
		}
		return "OK";
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		pd.setMessage("Checking data("+values[0]+"/"+tables.length+")...");
	}
	
	@Override
	protected void onPostExecute(String result) {
		onSuccess(result);
	}

	public void onSuccess(String res) {}
	
	
	private void getDataTable(int index) throws JSONException, ClientProtocolException, IOException{
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(Constants.WS_PATH + "getDataTable.php");
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("tbName", tables[index]));
		httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

		HttpResponse response = httpclient.execute(httppost);

		HttpEntity entity = response.getEntity();
		if (entity != null) {
			// get the response content as a string
			InputStream instream = entity.getContent();
			BufferedReader reader = new BufferedReader(
					new InputStreamReader(instream, "UTF-8"));
			String line;
			StringBuilder sb = new StringBuilder("");
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		
		
			Log.i("XXX", tables[index] + "==>" + sb.toString());
			
			JSONArray array = new JSONArray(sb.toString());
			switch (index) {
			case 0: // CATEGORIES TABLE
				if(prefs.getString("CATEGORIES", "").equals(sb.toString())){
					break;
				}else{
					edt.putString("CATEGORIES", sb.toString());
					DataBaseManager.getInstance().clearTable(tables[index]);
					
					for (int i = 0; i < array.length(); i++) {
						JSONObject json = array.getJSONObject(i);
						mDB.addCategories(json.getInt("id"),
								json.getString("name"), json.getString("img_path"));
					}
				}
				break;
			case 1: // CUSTOM_INGREDIENTS TABLE
				if(prefs.getString("CUSTOM_INGREDIENTS", "").equals(sb.toString())){
					break;
				}else{
					edt.putString("CUSTOM_INGREDIENTS", sb.toString());
					DataBaseManager.getInstance().clearTable(tables[index]);
					
					for (int i = 0; i < array.length(); i++) {
						JSONObject json = array.getJSONObject(i);
						mDB.addCustomIngredients(json.getInt("id"),
								json.getString("text"), json.getInt("recipe_id"));
					}
				}
				break;
			case 2: // DIRECTIONS TABLE
				if(prefs.getString("DIRECTIONS", "").equals(sb.toString())){
					break;
				}else{
					edt.putString("DIRECTIONS", sb.toString());
					
					for (int j = 0; j < array.length(); j++) {
						JSONObject json = array.getJSONObject(j);
						mDB.addDirections(json.getInt("id"),
								json.getString("text"), json.getInt("recipe_id"), json.getInt("ordering"));
					}
				}
				break;
			case 3: // ING_GROUPS TABLE
				if(prefs.getString("ING_GROUPS", "").equals(sb.toString())){
					break;
				}else{
					edt.putString("ING_GROUPS", sb.toString());
					DataBaseManager.getInstance().clearTable(tables[index]);
					
					for (int j = 0; j < array.length(); j++) {
						JSONObject json = array.getJSONObject(j);
						mDB.addIngGroup(json.getInt("id"),
								json.getString("name"), json.getInt("recipe_id"));
					}
				}
				break;
			case 4: // INGREDIENTS TABLE
				if(prefs.getString("INGREDIENTS", "").equals(sb.toString())){
					break;
				}else{
					edt.putString("INGREDIENTS", sb.toString());
					
					for (int j = 0; j < array.length(); j++) {
						JSONObject json = array.getJSONObject(j);
						mDB.addIngredients(json.getInt("id"),
								json.getInt("is_added_cart"), json.getString("text"), json.getInt("ing_group_id"));
					}
				}
				break;
			case 5: // SUB_CATEGORY_RELATION TABLE
				if(prefs.getString("SUB_CATEGORY_RELATION", "").equals(sb.toString())){
					break;
				}else{
					edt.putString("SUB_CATEGORY_RELATION", sb.toString());
					DataBaseManager.getInstance().clearTable(tables[index]);
					
					for (int j = 0; j < array.length(); j++) {
						JSONObject json = array.getJSONObject(j);
						mDB.addRecipeSubCategoryRelation(json.getInt("id"),
								json.getInt("recipe_id"), json.getInt("sub_category_id"));
					}
				}
				break;
			case 6: // RECIPES TABLE
				if(prefs.getString("RECIPES", "").equals(sb.toString())){
					break;
				}else{
					edt.putString("RECIPES", sb.toString());
					DataBaseManager.getInstance().clearTable(tables[index]);
					
					for (int j = 0; j < array.length(); j++) {
						JSONObject json = array.getJSONObject(j);
						mDB.addRecipe(json.getInt("has_pdf"),
								json.getInt("is_added_cart"), json.getInt("id"),
								json.getString("name"), json.getString("description"),
								json.getString("serves"), json.getString("img_path"),
								json.getString("thumbnail_img_path"), json.getInt("is_fav"));
					}
				}
				break;
			case 7: // SUB_CATEGORIES TABLE
				if(prefs.getString("SUB_CATEGORIES", "").equals(sb.toString())){
					break;
				}else{
					edt.putString("SUB_CATEGORIES", sb.toString());
					DataBaseManager.getInstance().clearTable(tables[index]);
					
					for (int j = 0; j < array.length(); j++) {
						JSONObject json = array.getJSONObject(j);
						mDB.addSubCategories(json.getInt("id"),
								json.getInt("category_id"), json.getString("name"));
					}
				}
				break;
			case 8: // TIPS TABLE
				if(prefs.getString("TIPS", "").equals(sb.toString())){
					break;
				}else{
					edt.putString("TIPS", sb.toString());
					DataBaseManager.getInstance().clearTable(tables[index]);
					
					for (int j = 0; j < array.length(); j++) {
						JSONObject json = array.getJSONObject(j);
						mDB.addTips(json.getInt("id"),
								json.getString("text"), json.getInt("recipe_id"), 
								json.getInt("ordering"));
					}
				}
				break;
			}
			
			edt.commit();
		}
	}
}
